<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鼠标按住移动元素</title>
    <style>
        #pink {
            position: absolute;
            left: 50px;
            top: 200px;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div style="display: flex;">
        <div id="pink"></div>
    </div>
</body>
<script>
    //移动元素
    let pink = document.getElementById('pink')
    let pinkWidCenter = pink.clientWidth / 2
    let pinkHeiCenter = pink.clientHeight / 2
    pink.onmousedown = (event) => {
        document.onmousemove = (e) => {
            e = e || window.event

            //鼠标点击的位置移动
            pink.style.left = (e.clientX - event.offsetX) + 'px'
            pink.style.top = (e.clientY - event.offsetY) + 'px'

            //元素中心位置移动
            // pink.style.left = (e.clientX - pinkWidCenter) + 'px'
            // pink.style.top = (e.clientY - pinkHeiCenter) + 'px'
        }
    }
    pink.onmouseup = () => {
        document.onmousemove = null
    }
</script>

</html>